package adminYoga

import (
	"duoke/model"
	"duoke/model/yogaModel"
	"duoke/service/common"
	"duoke/tables"
	utils "duoke/utils/common"
	"duoke/utils/gconv"
	"duoke/utils/gjson"
	"duoke/utils/request"
	"duoke/utils/response"
	"duoke/utils/valid"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

var Date = new(dateCtl)

type dateCtl struct{}

func (ctl *dateCtl) Save(c *gin.Context) {
	var req yogaModel.ReqDateList
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	toMap, err := utils.Common.StructToMap(req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	toMap["reservation_morning"] = gjson.StructOrMap2Json(req.ReservationMorning)
	toMap["reservation_afternoon"] = gjson.StructOrMap2Json(req.ReservationAfternoon)
	err = common.Tales.Save(c, toMap, "yoga_date")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", nil)
}

func (ctl *dateCtl) List(c *gin.Context) {
	var req model.ReqList
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	var list []yogaModel.ReqJoinDate
	count, err := common.Tales.JoinList(c, &req).Table("yoga_date as d").
		Where("d.deleted_at is null").
		Join("LEFT", "yoga_group_class as gc", "d.class_id=gc.id").
		Cols("d.*", "gc.name as class_name").
		FindAndCount(&list)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", gin.H{"total": count, "list": list})
}
func (ctl *dateCtl) Info(c *gin.Context) {
	req := request.JsonMap(c)
	id := gconv.Int(req["id"])
	if id == 0 {
		response.Error(c, "参数缺失【id】", nil)
		return
	}
	where := fmt.Sprintf("id=%d", id)
	var m yogaModel.ReqDate
	get, err := common.Tales.Info(where, "*").Table("yoga_date").Get(&m)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if !get {
		response.Error(c, "数据不存在", nil)
		return
	}
	response.Success(c, "success", m)
}
func (ctl *dateCtl) Del(c *gin.Context) {
	req := request.JsonMap(c)
	id := gconv.Int(req["id"])
	if id == 0 {
		response.Error(c, "参数缺失【id】", nil)
		return
	}
	where := fmt.Sprintf("id=%d", id)
	get, err := common.Tales.Info(where, "*").Delete(&tables.YogaDate{})
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", get)
}
